<?php
class Topics extends Public_Controller
{
	public function __construct()
	{
		parent::__construct();
	}
	
	public function index()
	{
		$data['topics'] = new Post;
		$data['topics']->where('topic_id <',1)->group_by('id')->group_by_related_reply('topic_id');
		$data['topics']->order_by_func('IFNULL',array('@MAX(reply_posts.id)','[,]','@id '),'desc');
		$data['topics']->get_page();
		$this->template->build('topics/index',$data);
	}
	
	public function view($id)
	{
		$data['topic'] = new Post($id);
		$data['topic']->counter('counter');
		$data['topics'] = new Post;
		$data['topics']->where('id',$id)->or_where('topic_id',$id)->order_by('id','asc')->get_page();
		$this->template->build('topics/view',$data);
	}
	
	public function form($id = NULL)
	{
		if(is_login())
		{ 
			$data['topic'] = (is_login() && ( user()->level_id < 3 OR user()->post->get_by_id($id)->id )) ? new Post($id) : new Post;
			//media
			$this->template->append_metadata('<script type="text/javascript" src="media/tiny_mce/tiny_mce.js"></script>');
			$this->template->append_metadata('<script type="text/javascript" src="media/js/tinymce.js"></script>');
			$this->template->build('topics/form',$data);
		}
		else
		{
			set_notify('error', '<strong>สำหรับสมาชิก</strong><br />กรุณาล็อคอินเพื่อเข้าใช้งาน');
			redirect($_SERVER['HTTP_REFERER']);
		}
	}
	
	public function save($id = NULL)
	{
		if($_POST)
		{
			$topic = (is_login() && ( user()->level_id < 3 OR user()->post->get_by_id($id)->id )) ? new Post($id) : new Post;
			$topic->from_array($_POST);
			if(!$id) $topic->user_id = user()->id;
			if($topic->id) $topic->modified = date('Y-m-d H:i:s');
			if(@$_POST['delete_image']==1)
			{
				$topic->delete_file('uploads/webboard/','image');
				$topic->image = NULL;
			}
			if($_FILES['image']['name'])
			{
				$topic->delete_file('uploads/webboard/','image');
				$topic->image = $topic->upload($_FILES['image'],'uploads/webboard/',600,600,'limit_x');
			}
			$topic->save();
			set_notify('success', lang('save_data_complete'));
		}
		redirect('webboard/topics/view/'.$topic->id);
	}
	
	public function delete($id = NULL)
	{
		$topic = (is_login() && ( user()->level_id < 3 OR user()->post->get_by_id($id)->id )) ? new Post($id) : new Post;
		if(is_login() && ( user()->level_id < 3 OR user()->id == $topic->user_id ))
		{
			foreach($topic->reply->get() as $reply) $reply->delete_file('uploads/webboard/','image');
			$topic->reply->delete_all();
			$topic->delete_file('uploads/webboard/','image');
			$topic->delete();
			set_notify('success', lang('delete_data_complete'));
		}
		redirect('webboard/topics');
	}	
} 
?>